import { asyncRoutes, constantRoutes } from "@/router";

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route, permission) {
  const { meta, children } = route;
  if (children && children.length) {
    if (meta && meta.roles) {
      return roles.some((role) => meta.roles.includes(role));
    }
    return false;
    const flag = children.some((item) => {
      const { meta } = item;
      if (meta) {
        if (meta.permission) {
          if (permission.find((per) => per === meta.permission)) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      } else {
        return true;
      }
    });
    return flag;
  }
  // if (meta) {
  //   if (meta.permission) {
  //     if (permission.find((per) => per === meta.permission)) {
  //       return true;
  //     } else {
  //       return false;
  //     }
  //   } else {
  //     return false;
  //   }
  // } else {
  //   return true;
  // }
}
/**
 * Filter asynchronous routing tables by recursion
 * @param asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(asyncRoutes, roles, permission) {
  const res = [];
  asyncRoutes.forEach((route) => {
    const tmp = { ...route };
    const flg = hasPermission(roles, tmp, permission);
    if (hasPermission(roles, tmp, permission)) {
      if (tmp.children) {
        // tmp.children = filterAsyncRoutes(tmp.children, roles, permission);
      }
      res.push(tmp);
    }
  });
  return res;
}

const state = {
  routes: [...constantRoutes, ...asyncRoutes],
  addRoutes: [],
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  },
};

const actions = {
  generateRoutes({ commit }, params) {
    const { role, permission } = params;
    const permissionData = permission === "" ? [] : JSON.parse(permission);
    return new Promise((resolve) => {
      let roles, accessedRoutes;
      switch (role) {
        case 1:
          roles = [1];
          break; // 管理员
        case 2:
          roles = [2];
          break; // 普通用户
      }
      accessedRoutes = filterAsyncRoutes(asyncRoutes, roles, permissionData);
      commit("SET_ROUTES", accessedRoutes);
      resolve(accessedRoutes);
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
